#!/data/data/com.termux/files/usr/bin/bash

TARBALL="rootfs.tar.xz"
LOCAL_SOURCE="/storage/emulated/0/uos/rootfs.tar.xz"
BIN_NAME="start-uos"

echo "[1/4] 安装依赖..."
apt update -y && apt install -y proot tar || {
    echo "错误: 依赖安装失败"
    exit 1
}

# 检查本地源文件是否存在
if [ ! -f "$LOCAL_SOURCE" ]; then
    echo "❌ 错误: 本地系统文件未找到: $LOCAL_SOURCE"
    echo "请确保文件已放置在指定路径"
    exit 1
fi

# 将文件复制到当前目录
echo "[2/4] 复制系统文件到 Termux..."
cp "$LOCAL_SOURCE" "./$TARBALL" || {
    echo "❌ 错误: 文件复制失败"
    exit 1
}

# 检查文件完整性
echo "验证文件完整性..."
if ! tar -tf "./$TARBALL" &> /dev/null; then
    echo "❌ 错误: 文件损坏或格式不正确"
    rm -f "./$TARBALL"
    exit 1
fi

if [ -d "uos-arm64/usr" ]; then
    echo "检测到已解压的系统，跳过解压..."
else
    echo "[3/4] 解压系统 (可能需要几分钟)..."
    mkdir -p "uos-arm64"
    tar -xJf "./$TARBALL" -C "uos-arm64" || {
        echo "❌ 错误: 解压失败！文件可能已损坏。"
        rm -f "./$TARBALL"
        exit 1
    }
    
    # 清理临时文件
    rm -f "./$TARBALL"
fi

echo "[4/4] 配置启动器和环境..."
# 创建启动脚本
cat > "$BIN_NAME" <<'EOF'
#!/bin/bash
pulseaudio --start
cd ~
unset LD_PRELOAD
command="proot"
command+=" --link2symlink"
command+=" -0"
command+=" -r uos-arm64"
command+=" -b /dev"
command+=" -b /proc"
command+=" -b uos-arm64/root:/dev/shm"
command+=" -w /root"
command+=" /usr/bin/env -i"
command+=" HOME=/root"
command+=" PATH=/usr/local/sbin:/usr/local/bin:/bin:/usr/bin:/sbin:/usr/sbin:/usr/games:/usr/local/games"
command+=" TERM=$TERM"
command+=" LANG=zh_CN.UTF-8"
command+=" /usr/bin/bash -login"
com="$@"
if [ -z "$1" ]; then
    exec $command
else
    $command -c "$com"
fi
EOF

# 安装到系统路径
cp "$BIN_NAME" ~/../usr/bin/
chmod +x ~/../usr/bin/"$BIN_NAME" "$BIN_NAME"

# 配置网络
echo "配置网络设置..."
cat > "uos-arm64/etc/hosts" <<EOF
127.0.0.1   localhost
::1         localhost ip6-localhost ip6-loopback
EOF

cat > "uos-arm64/etc/resolv.conf" <<EOF
nameserver 8.8.8.8
nameserver 8.8.4.4
nameserver 2001:4860:4860::8888
nameserver 2001:4860:4860::8844
EOF

chmod 644 "uos-arm64/etc/hosts" "uos-arm64/etc/resolv.conf"

echo "安装完成！"
echo "使用命令 \`$BIN_NAME\` 启动 UOS 系统。"
echo "默认用户名: root"
echo "默认密码: 无"